import React, { useState } from "react";
import {
  Box,
  Typography,
  Grid,
  Card,
  CardContent,
  Button,
  TextField,
  Select,
  MenuItem,
  IconButton,
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableRow,
  Pagination,
  InputAdornment,
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  Snackbar,
  Stack,
  Chip,
    CssBaseline,
  ThemeProvider,
} from "@mui/material";
import { Search, Settings, Delete, Save, ArrowForwardIos } from "@mui/icons-material";
import theme from "../themes/theme ";
import { DragDropContext, Droppable, Draggable } from "react-beautiful-dnd";

// 日期时间选择器
import { LocalizationProvider } from "@mui/x-date-pickers/LocalizationProvider";
import { AdapterDayjs } from "@mui/x-date-pickers/AdapterDayjs";
import { DateTimePicker } from "@mui/x-date-pickers/DateTimePicker";
import dayjs, { Dayjs } from "dayjs";


const initialSteps = ["提交评估", "部门审核", "专家评审", "最终归档"];

const mockReports = [
  { name: "2025年度数字化能力评估报告", year: "2025", type: "年度", unit: "全公司", date: "2025-06-19", status: "已归档" },
  { name: "Q1季度数字化转型进度报告", year: "2025", type: "季度", unit: "部门", date: "2025-03-31", status: "已归档" },
  { name: "数据管理专项评审报告", year: "2025", type: "专项", unit: "数据中心", date: "2025-05-20", status: "审核中" },
  { name: "营销部门数字化评估报告", year: "2024", type: "部门", unit: "营销部", date: "2024-12-15", status: "已归档" }
];

export default function AuditArchivePage() {
  // 流程
  const [steps, setSteps] = useState(initialSteps);
  const [newStep, setNewStep] = useState("");

  // 调阅
  const [search, setSearch] = useState("");
  const [filterYear, setFilterYear] = useState("全部");
  const [filterStatus, setFilterStatus] = useState("全部");
  const [page, setPage] = useState(1);

  // 定时归档
  const [openDialog, setOpenDialog] = useState(false);
  const [scheduleTime, setScheduleTime] = useState<Dayjs | null>(dayjs().add(1, "hour"));
  const [scheduleNote, setScheduleNote] = useState("年度报告归档");
  const [snackbarOpen, setSnackbarOpen] = useState(false);

  // —— 拖拽 —— //
  const handleDragEnd = (result: any) => {
    if (!result.destination) return;
    const reordered = Array.from(steps);
    const [removed] = reordered.splice(result.source.index, 1);
    reordered.splice(result.destination.index, 0, removed);
    setSteps(reordered);
  };

  const addStep = () => {
    if (!newStep.trim()) return;
    setSteps((prev) => [...prev, newStep.trim()]);
    setNewStep("");
  };

  const removeStep = (idx: number) => {
    setSteps((prev) => prev.filter((_, i) => i !== idx));
  };

  // —— 搜索/筛选/分页 —— //
  const filteredReports = mockReports.filter((r) => {
    const matchSearch = r.name.includes(search);
    const matchYear = filterYear === "全部" || r.year === filterYear;
    const matchStatus = filterStatus === "全部" || r.status === filterStatus;
    return matchSearch && matchYear && matchStatus;
  });
  const itemsPerPage = 3;
  const paginatedReports = filteredReports.slice((page - 1) * itemsPerPage, page * itemsPerPage);

  // —— 归档动作 —— //
  const handleArchiveNow = () => {
    setSnackbarOpen(true);
  };

  const handleScheduleConfirm = () => {
    // 这里可对接后端：保存定时任务 { time: scheduleTime?.toISOString(), note: scheduleNote, steps }
    setOpenDialog(false);
    setSnackbarOpen(true);
  };

  return (
    <ThemeProvider theme={theme}>
      <CssBaseline />
      <LocalizationProvider dateAdapter={AdapterDayjs}>
        <Box sx={{ minHeight: "100vh", bgcolor: "background.default", color: "#fff", p: 3 }}>
          {/* 标题 */}
          <Typography variant="h4" gutterBottom align="center">
            评估审核与归档
          </Typography>
          <Typography variant="body1" align="center" sx={{ mb: 4 }}>
            支持企业数智化能力评估结果的审核流程定制化与节点流转，以及结果的归档与调阅。
          </Typography>

          <Grid container spacing={3}>
            {/* 审核流程定制化 */}
            <Grid item xs={12} md={6}>
              <Card>
                <CardContent>
                  <Typography variant="h6" gutterBottom>
                    审核流程定制化
                  </Typography>

                  {/* 节点编辑区（拖拽） */}
                  <Box sx={{ display: "flex", gap: 2, mb: 2 }}>
                    <TextField
                      size="small"
                      placeholder="新增节点，如：法务复核"
                      value={newStep}
                      onChange={(e) => setNewStep(e.target.value)}
                    />
                    <Button variant="contained" onClick={addStep}>
                      添加
                    </Button>
                    <IconButton color="primary" title="保存流程（可对接后端）">
                      <Save />
                    </IconButton>
                  </Box>

                  <DragDropContext onDragEnd={handleDragEnd}>
                    <Droppable droppableId="steps">
                      {(provided) => (
                        <Box ref={provided.innerRef} {...provided.droppableProps}>
                          {steps.map((step, index) => (
                            <Draggable key={`${step}-${index}`} draggableId={`${step}-${index}`} index={index}>
                              {(provided, snapshot) => (
                                <Box
                                  ref={provided.innerRef}
                                  {...provided.draggableProps}
                                  {...provided.dragHandleProps}
                                  sx={{
                                    display: "flex",
                                    justifyContent: "space-between",
                                    alignItems: "center",
                                    bgcolor: snapshot.isDragging ? "#2b3e66" : "#263859",
                                    p: 1,
                                    borderRadius: 1,
                                    mb: 1,
                                    transition: "background 0.2s"
                                  }}
                                >
                                  <Typography>{step}</Typography>
                                  <IconButton color="secondary" onClick={() => removeStep(index)}>
                                    <Delete />
                                  </IconButton>
                                </Box>
                              )}
                            </Draggable>
                          ))}
                          {provided.placeholder}
                        </Box>
                      )}
                    </Droppable>
                  </DragDropContext>

                  {/* —— 流程预览（箭头连线） —— */}
                  <Typography variant="subtitle2" sx={{ mt: 2, mb: 1, opacity: 0.85 }}>
                    流程预览
                  </Typography>
                  <Stack
                    direction="row"
                    alignItems="center"
                    flexWrap="wrap"
                    gap={1}
                    sx={{
                      p: 1.5,
                      borderRadius: 1.5,
                      bgcolor: "#1e2d4a",
                      boxShadow: "inset 0 0 0 1px rgba(255,255,255,0.06)"
                    }}
                  >
                    {steps.map((s, i) => (
                      <React.Fragment key={`preview-${s}-${i}`}>
                        <Chip
                          label={s}
                          variant="filled"
                          sx={{
                            bgcolor: i === steps.length - 1 ? "warning.main" : "info.main",
                            color: "#00131a",
                            fontWeight: 600
                          }}
                        />
                        {i < steps.length - 1 && <ArrowForwardIos fontSize="small" sx={{ opacity: 0.7 }} />}
                      </React.Fragment>
                    ))}
                  </Stack>
                </CardContent>
              </Card>
            </Grid>

            {/* 评估结果调阅 */}
            <Grid item xs={12} md={6}>
              <Card>
                <CardContent>
                  <Typography variant="h6" gutterBottom>
                    评估结果调阅
                  </Typography>
                  <Box sx={{ display: "flex", gap: 2, mb: 2 }}>
                    <TextField
                      fullWidth
                      size="small"
                      placeholder="搜索归档评估报告..."
                      value={search}
                      onChange={(e) => setSearch(e.target.value)}
                      InputProps={{
                        startAdornment: (
                          <InputAdornment position="start">
                            <Search />
                          </InputAdornment>
                        )
                      }}
                    />
                  </Box>
                  <Box sx={{ display: "flex", gap: 2, mb: 2 }}>
                    <Select size="small" value={filterYear} onChange={(e) => setFilterYear(e.target.value)}>
                      <MenuItem value="全部">全部年度</MenuItem>
                      <MenuItem value="2025">2025</MenuItem>
                      <MenuItem value="2024">2024</MenuItem>
                    </Select>
                    <Select size="small" value={filterStatus} onChange={(e) => setFilterStatus(e.target.value)}>
                      <MenuItem value="全部">全部状态</MenuItem>
                      <MenuItem value="已归档">已归档</MenuItem>
                      <MenuItem value="审核中">审核中</MenuItem>
                    </Select>
                  </Box>

                  <Table size="small">
                    <TableHead>
                      <TableRow>
                        <TableCell>报告名称</TableCell>
                        <TableCell>年度</TableCell>
                        <TableCell>类型</TableCell>
                        <TableCell>单位</TableCell>
                        <TableCell>状态</TableCell>
                      </TableRow>
                    </TableHead>
                    <TableBody>
                      {paginatedReports.map((report, index) => (
                        <TableRow key={index}>
                          <TableCell>{report.name}</TableCell>
                          <TableCell>{report.year}</TableCell>
                          <TableCell>{report.type}</TableCell>
                          <TableCell>{report.unit}</TableCell>
                          <TableCell>{report.status}</TableCell>
                        </TableRow>
                      ))}
                    </TableBody>
                  </Table>
                  <Box sx={{ display: "flex", justifyContent: "center", mt: 2 }}>
                    <Pagination
                      count={Math.ceil(filteredReports.length / itemsPerPage)}
                      page={page}
                      onChange={(_, v) => setPage(v)}
                      color="primary"
                    />
                  </Box>
                </CardContent>
              </Card>
            </Grid>

            {/* 评估结果归档 */}
            <Grid item xs={12}>
              <Card>
                <CardContent>
                  <Typography variant="h6" gutterBottom>
                    评估结果归档
                  </Typography>
                  <Box sx={{ display: "flex", gap: 2, mb: 2 }}>
                    <TextField
                      label="归档描述"
                      size="small"
                      fullWidth
                      value={scheduleNote}
                      onChange={(e) => setScheduleNote(e.target.value)}
                    />
                    <TextField label="关键词" size="small" fullWidth defaultValue="国际标准模型V1.0" />
                  </Box>
                  <Box sx={{ display: "flex", gap: 2 }}>
                    <Button variant="contained" onClick={handleArchiveNow}>
                      立即归档
                    </Button>
                    <Button variant="outlined" onClick={() => setOpenDialog(true)}>
                      定时归档
                    </Button>
                    <Button variant="outlined" startIcon={<Settings />}>
                      归档设置
                    </Button>
                  </Box>
                </CardContent>
              </Card>
            </Grid>
          </Grid>

          {/* 定时归档对话框（含日期时间选择器） */}
          <Dialog open={openDialog} onClose={() => setOpenDialog(false)} fullWidth maxWidth="sm">
            <DialogTitle>设置定时归档</DialogTitle>
            <DialogContent sx={{ pt: 2 }}>
              <Stack spacing={2}>
                <DateTimePicker
                  label="执行时间"
                  value={scheduleTime}
                  onChange={(v) => setScheduleTime(v)}
                  slotProps={{
                    textField: { size: "small", fullWidth: true }
                  }}
                  disablePast
                />
                <TextField
                  label="备注"
                  size="small"
                  fullWidth
                  value={scheduleNote}
                  onChange={(e) => setScheduleNote(e.target.value)}
                  placeholder="例如：季度归档任务"
                />
                <Box sx={{ p: 1, borderRadius: 1, bgcolor: "background.paper", opacity: 0.85 }}>
                  <Typography variant="caption">
                    将按所选时间触发归档任务。当前流程：{steps.join(" → ")}
                  </Typography>
                </Box>
              </Stack>
            </DialogContent>
            <DialogActions>
              <Button onClick={() => setOpenDialog(false)}>取消</Button>
              <Button variant="contained" onClick={handleScheduleConfirm} disabled={!scheduleTime}>
                确认
              </Button>
            </DialogActions>
          </Dialog>

          {/* 成功提示 */}
          <Snackbar
            open={snackbarOpen}
            autoHideDuration={3000}
            onClose={() => setSnackbarOpen(false)}
            message="操作成功"
          />
        </Box>
      </LocalizationProvider>
    </ThemeProvider>
  );
}
